package com.cloud.basic.video;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class getVideo {

    @GetMapping("/getVideo")
    public void getVideo(HttpServletRequest request, HttpServletResponse response){
        File file = new File("U:\\messes\\video");
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            String range = request.getHeader("Range");
            String[] rs = range.split("\\=");
            range = rs[1].split("\\-")[0];
            in = new FileInputStream(file);
            long length = file.length();
            int irange = Integer.parseInt(range);
            length = length - irange;
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Length", length + "");
            response.addHeader("Content-Range", "bytes " + range + "-" + length + "/" + length);
            response.addHeader("Content-Type", "audio/mpeg;charset=UTF-8");
            out = response.getOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            in.read();
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
